package com.ztesoft.zsmart.zcm.monitor.utils;

import com.ztesoft.zsmart.zmc.core.utils.StringHelper;
import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public final class FileHelper {
    private static final Logger logger = LoggerFactory.getLogger(FileHelper.class);

    private static final Map<String, String> LEGAL_CHAR_MAP = new HashMap<String, String>() {
        {
            put("a", "a");
            put("b", "b");
            put("c", "c");
            put("d", "d");
            put("e", "e");
            put("f", "f");
            put("g", "g");
            put("h", "h");
            put("i", "i");
            put("j", "j");
            put("k", "k");
            put("l", "l");
            put("m", "m");
            put("n", "n");
            put("o", "o");
            put("p", "p");
            put("q", "q");
            put("r", "r");
            put("s", "s");
            put("t", "t");
            put("u", "u");
            put("v", "v");
            put("w", "w");
            put("x", "x");
            put("y", "y");
            put("z", "z");
            put("a".toUpperCase(), "a".toUpperCase());
            put("b".toUpperCase(), "b".toUpperCase());
            put("c".toUpperCase(), "c".toUpperCase());
            put("d".toUpperCase(), "d".toUpperCase());
            put("e".toUpperCase(), "e".toUpperCase());
            put("f".toUpperCase(), "f".toUpperCase());
            put("g".toUpperCase(), "g".toUpperCase());
            put("h".toUpperCase(), "h".toUpperCase());
            put("i".toUpperCase(), "i".toUpperCase());
            put("j".toUpperCase(), "j".toUpperCase());
            put("k".toUpperCase(), "k".toUpperCase());
            put("l".toUpperCase(), "l".toUpperCase());
            put("m".toUpperCase(), "m".toUpperCase());
            put("n".toUpperCase(), "n".toUpperCase());
            put("o".toUpperCase(), "o".toUpperCase());
            put("p".toUpperCase(), "p".toUpperCase());
            put("q".toUpperCase(), "q".toUpperCase());
            put("r".toUpperCase(), "r".toUpperCase());
            put("s".toUpperCase(), "s".toUpperCase());
            put("t".toUpperCase(), "t".toUpperCase());
            put("u".toUpperCase(), "u".toUpperCase());
            put("v".toUpperCase(), "v".toUpperCase());
            put("w".toUpperCase(), "w".toUpperCase());
            put("x".toUpperCase(), "x".toUpperCase());
            put("y".toUpperCase(), "y".toUpperCase());
            put("z".toUpperCase(), "z".toUpperCase());

            put("0", "0");
            put("1", "1");
            put("2", "2");
            put("3", "3");
            put("4", "4");
            put("5", "5");
            put("6", "6");
            put("7", "7");
            put("8", "8");
            put("9", "9");
            put("/", "/");
            put("\\", "\\");
            put(".", ".");
            put("-", "-");
            put("_", "_");
            put(":", ":");
        }
    };

    private FileHelper() {

    }

    public static String canonicalizeUrl(String url) {
        return url.replace("\\", "").replace("..", "");
    }

    /**
     * 根据文件名读取返回字符串
     */
    public static String readFile(String fileName) {
        String content = "";
        try {
            content = FileUtils.readFileToString(new File(fileName));
        }
        catch (IOException e) {
            logger.error("", e);
        }

        return content;
    }

    /**
     * 写入一个文件
     */
    public static boolean writeFile(String fileName, String content) {
        try {
            FileUtils.writeStringToFile(new File(fileName), content);
        }
        catch (IOException e) {
            return false;
        }
        return true;
    }

    /**
     * 强制删除一个文件
     */
    public static boolean deleteForce(String fileName) {
        return FileUtils.deleteQuietly(new File(fileName));
    }

    /**
     * 将多个字符串拼接程一个完整的文件路径，使用本地路径格式
     */
    public static String buildLocalPath(String... strs) {
        String rslt = StringHelper.buildPath(File.separator, strs);
        // 转换成本地格式的目录
        rslt = rslt.replace("/", File.separator);
        rslt = rslt.replace("\\", File.separator);
        return rslt;
    }

    /**
     * 从一个文件中读取内容并转换为JSON对象，如果解析失败，就把文件清掉，因为文件可能不正常 返回null表示读取失败，可能为空，可能为格式有问题
     */
    public static JSONObject getJSONObjectFromFile(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            logger.warn("File [{}] not exits!", fileName);
        }
        else {
            try {
                String content = FileUtils.readFileToString(file);
                if (content.length() < 1) {
                    logger.debug("File [{}] empty!", fileName);
                }
                else {
                    try {
                        return JSONObject.fromObject(content);
                    }
                    catch (JSONException e) {
                        logger.warn("illigel json string [{}]", content);
                        file.delete(); // 删除这个无效的文件
                    }
                }
            }
            catch (Exception e) {
                logger.error("Unknown error", e);
            }
        }
        return null;
    }

    /**
     * 从一个文件中读取内容并转换为JSON对象，如果解析失败，就把文件清掉，因为文件可能不正常 返回null表示读取失败，可能为空，可能为格式有问题
     */
    public static JSONArray getJSONArrayFromFile(String fileName) {
        File file = new File(fileName);
        if (!file.exists()) {
            logger.warn("File [{}] not exits!", fileName);
        }
        else {
            try {
                String content = FileUtils.readFileToString(file);
                if (content.length() < 1) {
                    logger.debug("File [{}] empty!", fileName);
                }
                else {
                    try {
                        return JSONArray.fromObject(content);
                    }
                    catch (JSONException e) {
                        logger.warn("illigel json string [{}]", content);
                        file.delete(); // 删除这个无效的文件
                    }
                }
            }
            catch (Exception e) {
                logger.error("Unknown error", e);
            }
        }
        return null;
    }

    public static String vaildFilePath(String filePath) {

        StringBuilder sb = new StringBuilder();

        if (filePath == null) {
            return sb.toString();
        }

        for (int i = 0; i < filePath.length(); i++) {
            Character curChar = null;
            Character nextChar = null;
            try {
                curChar = filePath.charAt(i);
                nextChar = filePath.charAt(i + 1);
            }
            catch (Exception e) {
                nextChar = null;
            }

            replaceIllegalChar(sb, curChar, nextChar);

        }

        return sb.toString();

    }

    private static void replaceIllegalChar(StringBuilder sb, Character curChar, Character nextChar) {
        if (curChar != null && LEGAL_CHAR_MAP.get(curChar.toString()) != null) {
            if (curChar == '\\') {
                String sysFileSeparator = File.separator;
                if (null != sysFileSeparator && sysFileSeparator.equals(curChar.toString())) {
                    sb.append(LEGAL_CHAR_MAP.get(curChar.toString()));
                }
            }
            else if (curChar != '.' || nextChar != null && nextChar != '.') {
                sb.append(LEGAL_CHAR_MAP.get(curChar.toString()));
            }
        }
    }


}
